const htmlWebpackPlugin = require('html-webpack-plugin')
const miniCssExtractPlugin = require('mini-css-extract-plugin')
const eslintWebpackPlugin = require('eslint-webpack-plugin')
const workboxWebpackPlugin = require('workbox-webpack-plugin')
const path = require('path')

module.exports = {
  entry: './src/index.ts',
  output: {
    // path: 文件输出目录，必须是绝对路径
    path: path.resolve(__dirname, '../dist'),
    // 入口文件打包输出文件名
    filename: 'js/[name].[contenthash:8].js',
    // 给打包输出的其他文件命名
    chunkFilename: 'js/[name].chunk.[contenthash:8][ext]',
    // 图片、字体等通过type:asset处理资源的命名方式
    assetModuleFilename: 'asset/[name].[contenthash:8][ext]',
    clean: true
  },
  // 用来设置引用模块
  resolve: {
    extensions: ['.ts', '.js']
  },
  module: {
    rules: [
      {
        oneOf: [
          {
            test: /\.html$/,
            loader: 'html-loader'
          },
          {
            test: /\.scss$/,
            use: [
              miniCssExtractPlugin.loader,
              'css-loader',
              {
                loader: 'postcss-loader',
                options: {
                  postcssOptions: {
                    plugins: ['postcss-preset-env'] // 能解决大多数样式兼容性问题
                  }
                }
              },
              'sass-loader'
            ]
          },
          {
            test: /\.ts$/,
            exclude: /node_modules/,
            use: [
              {
                loader: 'babel-loader',
                options: {
                  cacheDirectory: true, //开启babel编译缓存
                  cacheCompression: false, //缓存文件不要压缩
                  plugins: ['@babel/plugin-transform-runtime'] //提取公用代码
                }
              },
              'ts-loader'
            ]
          },
          {
            test: /\.(png|jpe?g|gif|webp)$/,
            type: 'asset',
            parser: {
              dataUrlCondition: {
                maxSize: 10 * 1024 // 小于10kb的图片会被base64处理
              }
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new eslintWebpackPlugin({
      context: path.resolve(__dirname, '../src'),
      exclude: 'node_modules',
      cache: true, //开启缓存
      cacheLocation: path.resolve(
        __dirname,
        '../node_modules/.cache/.eslintcache'
      ) //缓存的目录
    }),
    new htmlWebpackPlugin({
      template: path.resolve(__dirname, '../public/index.html')
    }),
    new miniCssExtractPlugin({
      filename: 'css/[name].css'
    }),
    // 离线访问
    new workboxWebpackPlugin.GenerateSW({
      clientsClaim: true,
      skipWaiting: true
    })
  ],
  optimization: {
    // 代码分割
    splitChunks: {
      chunks: 'all'
    },
    //提取runtime文件
    runtimeChunk: {
      name: (entryponit) => `runtime~${entryponit.name}` // runtime文件命名规则
    }
  },
  mode: 'production',
  devtool: 'source-map'
}
